package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CheckgroupService;
import com.itheima.service.SetmealService;
import com.itheima.utils.QcloudUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.*;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private FreeMarkerConfigurer freemarkerConfig;
    @Value("${out_put_path}")
    private String out_put_path;
//    @Autowired
//    private JedisPool jedisPool;


    @Override
    public void Test() {

    }

    @Override
    public List<Setmeal> getSetmeal() {
        List<Setmeal> setmeal = setmealDao.getSetmeal();
        return setmeal;
    }

    @Override
    public Setmeal setmealInfoById(Integer setmealId) {
        Setmeal setmeal = setmealDao.setmealInfoById(setmealId);
        return setmeal;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        // 执行分页查询获取到套餐
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.findPage(queryString);
        // 获取套餐对应的检查组
        for (Setmeal setmeal : page) {
            List<CheckGroup> itemIdByGroup = setmealDao.findCheckGroupBySetmeal(setmeal.getId());
            setmeal.setCheckGroups(itemIdByGroup);
        }
        return new PageResult(page.getTotal(),page.getResult());
    }
    @Override
    public void add(Map<String,Object> map) {
        Object setmealOBJ =  map.get("setmeal");
        Object checkGroupIdsOBJ =map.get("checkGroupIds");
        // 解析为setmeal对象
        String setmealSTR = JSONObject.toJSONString(setmealOBJ);
        Setmeal setmeal = JSONObject.parseObject(setmealSTR, Setmeal.class);
        // 解析为list集合
        String checkGroupIdsSTR = JSONObject.toJSONString(checkGroupIdsOBJ);
        List<Integer> checkGroup = JSONObject.parseObject(checkGroupIdsSTR, List.class);

        // 添加套餐:新增后把id拿回来
        setmealDao.addsetmeal(setmeal);
        // 添加对应的关系到中间表
        for (Integer itemId : checkGroup) {
            setmealDao.addRefer(setmeal.getId(),itemId);
        }
//        if (setmeal.getImg()!=null){
////        保存数据库后在存到redis中
//        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
//        }
//        添加套餐后更新静态的套餐/套餐详情页面
//        generateHtml();
    }
    public void generateHtml(){
        System.out.println("开始了");
        // 查询所有的套餐(没有具体的信息)
        List<Setmeal> setmealList = setmealDao.getSetmeal();
//        生成套餐列表的静态页面
        try {
            generateSetmealHtml(setmealList);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        生成套餐详情的静态页面
        try {
            generateSetmealDetailHtml(setmealList);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void generateSetmealHtml(List<Setmeal> setmealList) throws Exception {
        // 创建数据对象
        Map<String,Object> map = new HashMap<>();
        map.put("setmealList",setmealList);
        executeGenerate("mobile_setmeal.ftl","setmeal.html",map);
    }

    public void generateSetmealDetailHtml(List<Setmeal> setmealList) throws Exception {
        //数据对象
        Map<String,Object> map=new HashMap<>();
        for (Setmeal setmeal : setmealList) {
            // 获取套餐详情
            Setmeal setmealInfoById = setmealDao.setmealInfoById(setmeal.getId());
            map.put("setmeal", setmealInfoById);
            //设置输出路径+文件名
            executeGenerate("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }

    }

    public void executeGenerate(String templateName,String htmlName,Map<String,Object> map) throws Exception {
        Template template = freemarkerConfig.getConfiguration().getTemplate(templateName);
        //设置输出路径+文件名
        OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(out_put_path +"/"+htmlName), "UTF-8");
        // 根据模板生成
        template.process(map,fileWriter);
        // 关流
        fileWriter.close();
    }
    @Override
    public String upload(MultipartFile imgFile) {
        // 上传过来的实际文件名
        String filenameUP = imgFile.getOriginalFilename();
        int i = filenameUP.lastIndexOf(".");
        String suffix = filenameUP.substring(i);
        // 真实使用的文件名
        String fileName = UUID.randomUUID().toString()+suffix;
        long size = imgFile.getSize();
        try {
            InputStream inputStream = imgFile.getInputStream();
            QcloudUtils.putObject(fileName, (FileInputStream) imgFile.getInputStream(),size);
        } catch (IOException e) {
            e.printStackTrace();
        }

//            把文件名上传到redis
//        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
        return fileName;
    }

    @Override
    public void edit(Map<String,Object> map) {
        Object checkGroupIdsOBJ = map.get("checkGroupIds");
        Object setmealOBJ =  map.get("setmeal");

        String checkGroupIdsSTR = JSONObject.toJSONString(checkGroupIdsOBJ);
        List<Integer> checkGroupIds = JSONObject.parseObject(checkGroupIdsSTR, List.class);


        String setmealSTR = JSONObject.toJSONString(setmealOBJ);
        Setmeal setmeal = JSONObject.parseObject(setmealSTR, Setmeal.class);


        // 先保存主体
        setmealDao.edit(setmeal);

        Integer setmealId = setmeal.getId();
        setmealDao.deleteRefer(setmealId);
        // 重新添加关系
        for (Integer itemId : checkGroupIds) {
            setmealDao.addRefer(setmealId,itemId);
        }


    }

    @Override
    public void delete(Integer id) {
        int i = setmealDao.setmeal4order(id);
        if (i!=0){
            // 套餐被订单关联了,不能删除
            throw new RuntimeException();
        }
        // 先删套餐关联的外键
        setmealDao.deleteRefer(id);
        // 再删主体
        setmealDao.delete(id);

    }
}
